package com.jdk21.core.utils;

import com.alibaba.fastjson2.JSON;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;

import java.io.StringWriter;
import java.util.Date;
import java.util.Map;
import java.util.Properties;

@Slf4j
public class VelocityUtil {

    private static String basePath = "templates/"; //resource目录下

    public static String getTemplateContent(String templateName, Map<String, Object> contextMap) {
        //初始化Velocity模板
        VelocityEngine velocityEngine = new VelocityEngine();

        try {
            Velocity.init();
            Properties properties = new Properties();
            properties.setProperty(Velocity.RESOURCE_LOADER, "class");
            properties.setProperty("class.resource.loader.class",
                    "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
            velocityEngine.init(properties);
        } catch (Exception e) {
            log.error("VelocityUtil.getTemplateContent error. templateName={} contextMap={}", templateName, JSON.toJSONString(contextMap), e);
        }

        //创建一个VeloctiyContext对象
        VelocityContext context = new VelocityContext();
        //向VelocityContext对象中放入一个键值对
        for (Map.Entry<String, Object> e : contextMap.entrySet()) {
            context.put(e.getKey(), e.getValue());
        }

        //创建一个输出流
        StringWriter writer = new StringWriter();
        try {
            //将模板与context中的对象结合，然后输出
            velocityEngine.mergeTemplate(basePath + templateName, "UTF-8", context, writer);
        } catch (Exception e) {
            log.error("Velocity模板引擎 error. templateName={} contextMap={}", templateName, JSON.toJSONString(contextMap), e);
        }
        return writer.toString();
    }

    public static void main(String[] args) {
        Map<String, Object> paramMap = Maps.newHashMap();
        paramMap.put("date", JodaTimeUtil.format(new Date()));
        String templateContent = getTemplateContent("auditPending.vm", paramMap);
        log.info("templateContent=\n{}", templateContent);
    }
}
